<?php
/**
 * Shop.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */
namespace data\service\Mine;

/**
 * 挖矿层
 */
use data\model\NsBuyCoinSendModel;
use data\model\NsCoinFundModel;
use data\model\NsCoinPriceModel;
use data\model\NsFloorModel;
use data\model\NsKefuModel;
use data\model\NsMemberInvestRecordsModel;
use data\model\NsRunMillModel;
use data\model\NsRunMillViewModel;
use data\model\NsTokenModel;
use data\model\NsTokenViewModel;
use data\model\NsTradeComplainModel;
use data\model\NsUblockRecordsModel;
use data\model\NsUblockViewModel;
use data\model\UserModel;
use data\service\BaseService as BaseService;
use data\model\NsMemberViewModel;
use data\model\NsCoinTradeModel;
use data\model\NsMemberAccountModel;
use data\model\NsMemberAccountRecordsModel;
use data\model\NsMillLevelModel;
use data\service\Member as MemberService;
use data\service\Member;
use data\service\Config;
use data\service\Salary;
use think;
use think\Cache as cache;

class Mine extends BaseService
{

    function __construct()
    {
        parent::__construct();
        $config = new Config();
        $key = "MATCH_RATE";
        $info = $config->getCacheConfig(0, $key);
        $this->match_rate = $info["value"];

    }

    // 发送众筹奖金
    public function sendFundSalary($uid,$total_price)
    {
        $member = new Member();
        $retval = $member->addMemberAccount(0, 1, $uid, $total_price, "通过债务审批");
        return $retval;
    }


    public function lastMineInfo($uid)
    {

        //个人上次挖矿情况
        $my_dig = $this->myLastDigInfo($uid);
        $my_current_info = $this->myCurrentStock($uid);
        $my_current_stock = $my_current_info["my_stock"];
        $my_ranking = $my_current_info["ranking"];
        $lastAverageMineInfo = $this->lastAverageMineInfo();
        $LastDigMaxDig = $this->getLastDigMaxDig();
        $all_stock = $this->getALLStock();
        $stock_info = $this->getStockInfo();

        $data = array(
            'my_dig' => (string)$my_dig,
            'average_dig' => (string)$lastAverageMineInfo,
            'max_dig' => (string)$LastDigMaxDig,
            'all_stock' => (string)$all_stock,
            'stock' => (string)$my_current_stock,
            'ranking' => (string)$my_ranking,
            'max_stock' => (string)$stock_info["max_stock"],
            'min_stock' => (string)$stock_info["min_stock"]
        );
        return $data;
    }

    //获取当前价格
    public function getCurPrice($time = 0 ,$cata = 0)
    {

        if($time == 0)
        {
            $time = date('Y-m-d',time());
        }
        trace("time","debug");
        trace($time,"debug");
        $cache = cache($time."price");
        $sell_price = cache($time."sell_price");
        if (empty($cache)) {
            $coinPrice = new NsCoinPriceModel();
            $res = $coinPrice->getInfo(['cur_time' => $time],"cur_price,sell_price");


            if($res)
            {
                $price = $res["cur_price"];
                $sell_price = $res["sell_price"];
            }else{

                $config = new Config();
                $key = "INC_PRICE";
                $info = $config->getCacheConfig(0, $key);
                $inc_price = $info["value"];

                $res = $coinPrice->getFirstData([],"cur_time desc");
                $cur_price = $res["cur_price"];
                $sell_price = $res["sell_price"];
                $res = $coinPrice->save(['cur_time' => $time,'sell_price'=>$sell_price,'cur_price' => $cur_price + $inc_price]);
                $res = $coinPrice->getInfo(['cur_time' => $time],"cur_price,sell_price");
                $price = $res["cur_price"];
                $sell_price = $res["sell_price"];
                $key = "delete_coin_trade";
                $array[] = array('instance_id' => $this->instance_id,'key' => 'delete_coin_trade', 'value' => 0);
                $res = $config->setConfig($array);
                Cache::set("delete_coin_trade", NULL, 1);
            }
            $cache = $price;
            cache($time."price",$price);
            cache($time."sell_price",$sell_price);
            if($cata == 0){
                return $cache;
            }else{
                return $sell_price;
            }

        } else {
            if($cata == 0){
                return $cache;
            }else{
                return $sell_price;
            }
        }

    }

    //我的当前算力,以及算力排行
    public function myCurrentStock($uid)
    {
        $memberAccount = new NsMemberAccountModel();

        $info = $memberAccount->getInfo(['uid'=>$uid],"*");

        $my_stock = $info["point"];

        $ranking = $memberAccount->getCount(['point' => array('gt',$my_stock)]) + 1;

        $data = array();

        $data["my_stock"] = $my_stock;
        $data["ranking"] = $ranking;
        return $data;


    }

    //获取最大算力及最小算力
    public function getStockInfo()
    {
        $memberAccount = new NsMemberAccountModel();
        $min_stock = $memberAccount->getMin(['point'=> array('gt',0)],"point");
        $max_stock = $memberAccount->getMax(['point'=> array('gt',0)],"point");
        if(is_null($min_stock))
        {
            $min_stock = 0;
        }
        if(is_null($max_stock))
        {
            $max_stock = 0;
        }

        $res["min_stock"] = $min_stock;
        $res["max_stock"] = $max_stock;

        return $res;
    }

    //我的上次挖矿值
    public function myLastDigInfo($uid)
    {
        $nsMemberAccountR = new NsMemberAccountRecordsModel();
        $myLastDigInfo = $nsMemberAccountR->getFirstData(['uid'=>$uid,'account_type' => 7,'from_type' => 10 ],"id desc");
        //$my_dig = $myLastDigInfo["number"];
        if($myLastDigInfo)
        {
            return $myLastDigInfo["number"];
        }
        else
        {
            return 0;
        }
    }


    //上次挖矿平均值
    public function lastAverageMineInfo()
    {
        $times = $this->getLastDigTimes();
        if($times > 1)
        {
            $nsMemberAccountR = new NsMemberAccountRecordsModel();
            $count = $nsMemberAccountR->getCount(['dig_times' => $times-1]);
            if($count)
            {
                $res = 50/$count;
            }
            else
            {
                $res = 0;
            }
            return $res;
        }
        return 0;

    }

    //获取全网算力
    public function getALLStock()
    {
        $memberAccount = new NsMemberAccountModel();

        $condition = array();
        $res = $memberAccount->getSum($condition,"point");

        if($res)
        {
            return $res;
        }
        else
        {
            return 0;
        }


    }

    //获取当前挖矿次数
    public function getLastDigTimes()
    {
        $account_record = new NsMemberAccountRecordsModel();

        $times = $account_record->getMax(['account_type' => 7] ,"dig_times");

        if($times)
        {
            $times = $times + 1;
        }
        else
        {
            $times = 1;
        }
        return $times;
    }

    //上次挖矿最大值
    public function getLastDigMaxDig()
    {
        $account_record = new NsMemberAccountRecordsModel();
        $time = $this->getLastDigTimes() - 1;
        $res = $account_record->getMax(['dig_times'=>$time],"number");
        if(!$res)
        {
            $res = 0;
        }
        return $res;
    }


    //挖一次矿
    public function addDigMine($send_money)
    {
        $memberAccount = new NsMemberAccountModel();
        //获取所有会员
        $page_index = 0;
        $page_size = 0;
        $condition["member_level"] = array('gt',47);
        $condition["point"] = array('gt',0);
        $member_view = new NsMemberViewModel();
        $order = '';
        $member_list = $member_view->getAllMember($page_index, $page_size, $condition, $order);

        $count = count($member_list);
        if($count <= 0)
        {
            return 1;
        }

        //获取全网算力
        $getALLStock = $this->getALLStock();

        //当前挖矿次数
        $times = $this->getLastDigTimes();

        $member = new MemberService();
        foreach($member_list as $value)
        {

            if($value["point"] > 0 and $getALLStock > 0)
            {
                $send_coin = $send_money*$value["point"]/$getALLStock;
                if($send_coin > 0.01)
                {
                    $retval = $member->addMemberAccount(0, 7, $value["uid"], $send_coin, "挖矿获取",10,$times);
                }
            }
        }

        return 1;
    }

    // 获得当前产出总数
    public function getAllReCount()
    {
        $run_mill = new NsRunMillModel();
        $condition = array();
        $count = $run_mill->getSum($condition,"al_product");
        trace($count,"debug");
        return $count;
    }

    // 获得当前求购总数
    public function getAllBuyCount()
    {
        //$coinTrade = new NsCoinTradeModel();
        //$res = $coinTrade->getSum(['trade_status' => 0],"coin_count");

        $match_rate = Cache::get("getAllBuyCount");
        if(empty($match_rate))
        {
            $config = new Config();
            $key = "match_rate";
            $info = $config->getConfig(0, $key);
            $match_rate = $info["value"];
            Cache::set("getAllBuyCount",$match_rate,30);
        }


        return $match_rate;
    }

    // 获取主流币行情
    public function coinInfo()
    {
        $list = Cache::get("coin_info_list");
        if(empty($list)) {

            $url = "https://api.coincap.io/v2/assets";
            $get_url = $url;
            $list = file_get_contents($get_url);
            Cache::set("coin_info_list", $list, 3600);
        }
        //trace($result,"debug");
        return $list;
    }


    // 获取交易订单数量
    public function getTradeCount($condition)
    {
        $trade = new NsCoinTradeModel();
        $count = $trade->getCount($condition);
        return $count;
    }


    // 获得当前交易总数
    public function getAllTradeCount()
    {
        $config = new Config();
        $key = "delete_coin_trade";
        $info = $config->getConfig(0, $key);
        $match_rate = $info["value"];
        return $match_rate;
    }

    // 获取交易中心购买单 显示今天的购买订单
    public function getCoinBuyList()
    {
        $list = Cache::get("buy_coin_list");
        if(empty($list)) {
            $coin_price = new NsCoinTradeModel();
            $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $condition = ['trade_status' => 0];
            $list = $coin_price->limit(0, 200)->where($condition)->order('tid desc')->select();
            $count = count($list);
            Cache::set("buy_coin_list", $list, $count);
        }
        return $list;
    }

    // 众筹交易详情
    public function getFunTradeDetail($id)
    {
        $trade = new NsCoinFundModel();
        $info = $trade->getInfo(['fid' => $id]);
        return $info;
    }

    // 获取正在审批金额
    public function getApplyAccount($condition)
    {
        $coin_fund = new NsCoinFundModel();
        $res = $coin_fund->getSum($condition,"total_price");
        return $res;
    }


    // 交易详情
    public function getCoinTradeDetail($id)
    {
        $trade = new NsCoinTradeModel();
        $info = $trade->getInfo(['tid' => $id]);
        $info['trade_status_word'] = $this->getTradeStatusWord($info['trade_status']);
        return $info;
    }


    public function getTradeStatusWord($trade_status)
    {
        if($trade_status == 0){return '待匹配';}
        if($trade_status == 1){return '待付款';}
        if($trade_status == 2){return '已支付';}
        if($trade_status == 3){return '已确认';}
        if($trade_status == -1){return '已违规';}
    }

    // 更改交易凭证
    public function ModifyTradePayPic($id,$pay_pic,$org_img)
    {
        $trade = new NsCoinTradeModel();
        $res = $trade->save(['pay_pic' => $pay_pic,'pay_org_pic'=>$org_img],['tid' => $id]);
        return $res;
    }

    // 删除昨日订单
    public function deleteYestodayTrade($beginToday)
    {
        $coin_price = new NsCoinTradeModel();
        $res = $coin_price->where(['add_time'=>['lt',$beginToday],'trade_status'=>0])->delete();;
    }



    public function getMemberAccountList($page_index, $page_size, $condition, $order = ' salary desc', $field = '*')
    {
        $member_account = new NsMemberAccountModel();
        $list = $member_account->getViewList($page_index, $page_size, $condition, $order);
        return $list;
    }

    /**
     * 众筹交易列表
     */
    public function getCoinFundList($page_index, $page_size, $condition, $order = 'nft.add_time desc', $field = '*')
    {
        $coin_price = new NsCoinFundModel();
        $list = $coin_price->getViewList($page_index, $page_size, $condition, $order);

        foreach ($list['data'] as $k => $v) {

            $member = new MemberService();

            if($v['op_uid'])
            {
                $sell_Info = $member->getUserInfoByUid($v['op_uid']);
                $list['data'][$k]['op_real_name'] = $sell_Info['real_name'];
                $list['data'][$k]['op_user_tel'] = $sell_Info['user_tel'];
            }
            else
            {
                $list['data'][$k]['op_real_name'] = "";
                $list['data'][$k]['op_user_tel'] = "";
            }
        }
        return $list;
    }


    /**
     * 众筹列表
     */
    public function getFundTradeList($page_index, $page_size, $condition, $order = 'nct.add_time desc', $field = '*')
    {
        $coin_price = new NsCoinFundModel();
        $list = $coin_price->getViewList($page_index, $page_size, $condition, $order);
        return $list;
    }

    /**
     * 交易列表
     */

    public function getCoinTradeList($page_index, $page_size, $condition, $order = 'nct.add_time desc', $field = '*')
    {
        $coin_price = new NsCoinTradeModel();
        $list = $coin_price->getViewList($page_index, $page_size, $condition, $order);
        $memberAccount = new NsMemberAccountModel();
        foreach ($list['data'] as $k => $v) {

            $member = new MemberService();

            $accInfo = $memberAccount->getInfo(['uid'=>$v['post_uid']],"*");
            $list['data'][$k]['post_point'] = $accInfo['point'];
            $list['data'][$k]['post_balance'] = $accInfo['balance'];
            $list['data'][$k]['post_donation'] = $accInfo['donation'];

            if($v['op_uid'])
            {
                $sell_Info = $member->getUserInfoByUid($v['op_uid']);
                $list['data'][$k]['op_real_name'] = $sell_Info['real_name'];
                $list['data'][$k]['op_user_tel'] = $sell_Info['user_tel'];
                $list['data'][$k]['op_user_ip'] = $sell_Info['current_login_ip'];
            }
            else
            {
                $list['data'][$k]['op_real_name'] = "";
                $list['data'][$k]['op_user_tel'] = "";
            }
            $list['data'][$k]['trade_status_word'] = $this->getTradeStatusWord($list['data'][$k]['trade_status']);
        }
        return $list;
    }

    /**
     * 获取银币列表
     * @param unknown $page_index
     * @param unknown $page_size
     * @param unknown $condition
     * @param string $order
     * @param string $field
     * @return multitype:number unknown
     */
    public function getCoinPriceList($page_index, $page_size, $condition, $order = '', $field = '*')
    {
        $coin_price = new NsCoinPriceModel();
        $list = $coin_price->getViewList($page_index, $page_size, $condition, $order);
        return $list;
    }

    // 添加客服
    public function addKefu($kf_name, $kf_qr, $kf_sort, $status,$kf_desc)
    {
        $mill_model = new NsKefuModel();
        $data = array(
            'kf_name'  => $kf_name,
            'kf_qr'  => $kf_qr,
            'kf_sort'  => $kf_sort,
            'status'  => $status,
            'kf_desc' => $kf_desc
        );
        $mill_model->save($data);
        return 1;
    }


    // 添加买币赠送规则
    public function addBuyCoinSend($buy_coin_count, $give_small, $give_middle, $give_large,$give_super)
    {
        $mill_model = new NsBuyCoinSendModel();
        $data = array(
            'buy_coin_count' => $buy_coin_count,
            'give_small'  => $give_small,
            'give_middle'  => $give_middle,
            'give_large'  => $give_large,
            'give_super'  => $give_super
        );
        $mill_model->save($data);
        return 1;
    }


    // 添加矿机
    public function addMill($shop_id,$level_name,$day_product,$total_product,$status,$mill_pic)
    {
        $mill_model = new NsMillLevelModel();
        $data = array(
            'shop_id' => 0,
            'level_name'  => $level_name,
            'day_product'  => $day_product,
            'total_product'  => $total_product,
            'status'  => $status,
            'mill_pic' => $mill_pic
        );
        $mill_model->save($data);
        return 1;
    }

    //添加币价
    public function addCoinPrice($cur_price,$cur_time,$sell_price = 0)
    {
        $coin_price = new NsCoinPriceModel();
        $data = array(
            'cur_price' => $cur_price,
            'cur_time'  => $cur_time,
            'sell_price' => $sell_price
        );
        strtotime($cur_time);
        $coin_price->save($data);

        trace('日期'.$cur_time,"debug");
        Cache::set($cur_time."price", NULL, 1);
        Cache::set($cur_time."sell_price", NULL, 1);
        return 1;
    }

    //已经提交众筹的数量
    public function getFundTradeCoin()
    {
        $coin_trade = new NsCoinFundModel();
        $count = $coin_trade->getSum(['uid'=>$this->uid,'trade_status'=>['gt',-1]],"coin_count");
        return $count;
    }


    //添加众筹购买记录
    public function buyFundTrade($coin_count,$coin_price,$desc,$trade_type = 1)
    {
        $member = new Member();
        $info = $member->getUserInfo();
        $add_time = time();
        $trade_no = time().rand(1000,9999);
        $coin_trade = new NsCoinFundModel();
        $data = array(
            'uid' => $this->uid,
            'coin_count'  => $coin_count,
            'coin_price' => $coin_price,
            'total_price' => $coin_price * $coin_count,
            'trade_status' =>0,
            'pay_pic'=>$desc,
            'add_time'  => $add_time,
            'trade_no'  => $trade_no,
            'trade_type' =>$trade_type
        );
        $coin_trade->save($data);
        return 1;
    }

    // 随机手机号
    public function randMobile($num = 1){
        //手机号2-3为数组
        $numberPlace = array(30,31,32,33,34,35,36,37,38,39,50,51,58,59,89);
        for ($i = 0; $i < $num; $i++){
            $mobile = 1;
            $mobile .= $numberPlace[rand(0,count($numberPlace)-1)];
            $mobile .= str_pad(rand(0,99999999),8,0,STR_PAD_LEFT);
            $result[] = $mobile;
        }
        return $result;
    }

    //添加购买记录
    public function buyCoinTrade($coin_count,$coin_price,$desc,$level_id = 0)
    {

        $member = new Member();
        $info = $member->getUserInfo();
        $post_real_name = substr_cut($info["real_name"]);
        $post_real_name = $info["nick_name"];
        if($desc == -1)
        {
            $post_user_tel = yc_phone($this->randMobile(1)[0]);
        }
        else
        {
            $post_user_tel = yc_phone($info["user_tel"]);
        }
        $add_time = time();
        $trade_no = time().rand(1000,9999);
        $coin_trade = new NsCoinTradeModel();
        $data = array(
            'post_uid' => $this->uid,
            'coin_count'  => $coin_count,
            'coin_price' => $coin_price,
            'total_price' => $coin_price * $coin_count,
            'trade_status' =>0,
            'trade_type'=>$desc,
            'add_time'  => $add_time,
            'trade_no'  => $trade_no,
            'post_real_name' => $post_real_name,
            'post_user_tel' => $post_user_tel,
            'level_id' => $level_id
        );
        $coin_trade->save($data);

        $user = new UserModel();

        $res = $user->save(['birthday'=>time()],['uid'=>$this->uid]);

        return 1;
    }


    //后台匹配
    public function backMatchingTrade($tid,$op_uid)
    {
        trace('后台匹配'.$tid.$op_uid,"debug");

        //查找数量对等的记录
        $trade_model = new NsCoinTradeModel();
        $res = $trade_model->where(['tid'=>$tid])->lock(true)->find();

        $post_uid = $res["post_uid"];
        $coin_count = $res["coin_count"];
        trace("订单状态".$res["trade_status"],"debug");
        if($res["trade_status"])
        {
            return 0;
        }

        // 如果是自己的订单则不能买卖
        if($post_uid == $op_uid)
        {
            return 0;
        }

        // 更改价格
        $coin_price = $this->getCurPrice();
        $data = array(
            'trade_status' => 1,
            'op_uid' => $op_uid,
            'trade_time' => time(),
            "coin_price" => $coin_price,
            "total_price" => $coin_count*$coin_price
        );
        $res = $trade_model->save($data,['tid'=> $tid]);

        trace("订单状态".$res,"debug");
        $this->clearCacheTradeList($op_uid);
        $this->clearCacheTradeList($post_uid);
        trace("提交事务".$res,"debug");
        return $tid;
    }

    public function matchingTrade($coin_count,$goods_discount,$tid = 0)
    {

        //查找数量对等的记录
        $trade_model = new NsCoinTradeModel();
        $trade_model->startTrans();
        try {

            if($tid == 0)
            {

                $today = strtotime(date('Y-m-d'));

                //$count = $trade_model->getCount(['add_time'=>['gt',$today],'trade_type' => 1,'coin_count'=>$coin_count,'trade_status'=>0,'post_uid'=>['neq',$this->uid]]);
                $count = $trade_model->getCount(['trade_type' => 1,'coin_count'=>$coin_count,'trade_status'=>0,'post_uid'=>['neq',$this->uid]]);

                if($count == 0)
                {
                    $condition = ['add_time'=>['gt',$today],'trade_status'=>0,'coin_count'=>$coin_count,'post_uid'=>['neq',$this->uid]];
                    //trace($condition,"debug");
                    $res = $trade_model->getFirstData($condition,"tid asc");

                    if($res)
                    {
                        $tid = $res["tid"];
                    }
                    else
                    {
                        $condition = ['trade_status'=>0,'coin_count'=>$coin_count,'post_uid'=>['neq',$this->uid]];
                        //trace($condition,"debug");
                        $res = $trade_model->getFirstData($condition,"tid desc");
                        $tid = $res["tid"];
                    }
                }
                else
                {
                    $condition = ['trade_type' => 1,'trade_status'=>0,'coin_count'=>$coin_count,'post_uid'=>['neq',$this->uid]];
                    //trace($condition,"debug");
                    $res = $trade_model->getFirstData($condition,"tid asc");
                    $tid = $res["tid"];
                }

            }

            //trace($tid,"debug");
            if($tid)
            {
                $trade_time = time();
                $data = ['trade_status' => 1,'op_uid' => $this->uid,'trade_time' => $trade_time];
                //trace("枷锁查询");
                $res = $trade_model->where(['tid'=>$tid])->lock(true)->find();

                $post_uid = $res["post_uid"];

                //trace("订单状态".$res["trade_status"]);
                if($res["trade_status"])
                {
                    $trade_model->rollback();
                    return 0;
                }

                // 如果是自己的订单则不能买卖
                if($post_uid == $this->uid)
                {
                    $trade_model->rollback();
                    return 0;
                }

                // 更改价格
                /*
                $coin_price = $this->getCurPrice();
                $data["coin_price"] = $coin_price;
                $data["total_price"] = $coin_count*$coin_price;
                */

                $res = $trade_model->save($data,['tid'=>$tid]);

                if($res!==false and $post_uid)
                {
                    $this->clearCacheTradeList($this->uid);
                    $this->clearCacheTradeList($post_uid);


                    //$config = new Config();

                    $rate = $goods_discount;
                    $info = $trade_model->getInfo(['tid'=>$tid]);
                    if($info['op_uid']== $this->uid) {
                        //减少
                        $member = new Member();
                        $retval = $member->addMemberAccount(0, 1, $this->uid, 0 - ($coin_count + $coin_count * $rate*0.01), '点对点交易,订单编号：' . $tid);
                    }
                    //trace($retval,"debug");
                    if($retval != 1)
                    {
                        $trade_model->rollback();
                        return 0;
                    }

                    $trade_model->commit();
                    return $tid;
                }
                else
                {
                    //trace("返回");
                    $trade_model->rollback();
                    return 0;
                }
            }
            else
            {
                $trade_model->rollback();
                return 0;
            }

        } catch (\Exception $e) {
            $trade_model->rollback();
            return 0;
        }
    }


    // 获取买币详情
    public function getBuyCoinSendInfo($id)
    {
        $mill = new NsBuyCoinSendModel();
        $info = $mill->getInfo(['id' => $id]);
        return $info;
    }

    // 获取矿机类型详情
    public function getRunMillInfo($run_mill_id)
    {
        $mill = new NsRunMillModel();
        $mill_run_info = $mill->getInfo(['run_mill_id' => $run_mill_id]);

        $mill_level_info = $this->getMillLevelInfo($mill_run_info['level_id']);
        $mill_run_info['mill_level_info'] = $mill_level_info;
        return $mill_run_info;
    }


    // 获取矿机类型详情
    public function getMillLevelInfo($level_id)
    {
        $mill = new NsMillLevelModel();
        $mill_level_info = $mill->getInfo(['level_id' => $level_id]);
        return $mill_level_info;
    }


    // 修改
    public function modifyBuyCoinSend($id,$give_small,$give_middle,$give_large,$give_super,$update_level,$give_parent)
    {
        $mill_model = new NsBuyCoinSendModel();
        $data = array(
            'give_small'  => $give_small,
            'give_middle'  => $give_middle,
            'give_large'  => $give_large,
            'give_super'  => $give_super,
            'update_level'  => $update_level,
            'give_parent'  => $give_parent
        );
        $mill_model->save($data,['id' => $id]);
        return 1;
    }
    //分页显示购买订单
    public function getBuyList($page_index,$buy_phone = '')
    {

        $condition["trade_status"] = 0;

        if($buy_phone)
        {
            $condition["post_user_tel"] = ['like',"%".$buy_phone];
        }

        $coin_price = new NsCoinTradeModel();
        $list = $coin_price->getViewList($page_index, 50, $condition, 'tid desc');
        $coin_price = $this->getCurPrice();
        foreach ($list['data'] as $k => $v) {

            $list['data'][$k]['coin_count'] = abs($v['coin_count']);
            //$list['data'][$k]['coin_price'] = round($coin_price,2);
            $list['data'][$k]['total_price'] =  $list['data'][$k]['coin_count'] * $list['data'][$k]['coin_price'];
        }
        //shuffle($list['data']);
        return $list;
    }


    // 修改矿机
    public function modifyMill($level_id,$level_name,$day_product,$total_product,$status,$mill_pic,$hour_product,$price,$add_hash,$all_day,$can_buy,$product_give,$product_desc)
    {
        $mill_model = new NsMillLevelModel();
        $data = array(
            'shop_id' => 0,
            'level_name'  => $level_name,
            'day_product'  => $day_product,
            'total_product'  => $total_product,
            'status'  => $status,
            'mill_pic' => $mill_pic,
            'hour_product'  => $hour_product,
            'add_hash' => $add_hash,
            'price' => $price,
            'all_day' => $all_day,
            'can_buy' => $can_buy,
            'product_give' => $product_give,
            'product_desc' => $product_desc
        );
        $mill_model->save($data,['level_id' => $level_id]);
        return 1;
    }

    //卖出币
    public function backSellCoinTrade($op_uid,$tid)
    {


        // 匹配算法
        $tid = $this->backMatchingTrade($tid,$op_uid);
        // 如果找到匹配记录进行交易
        if($tid)
        {
            trace("如果找到匹配记录进行交易".$tid);
            $this->sendMsg($tid);
            return 1;
        }
        return 0;
    }

    //卖出币
    public function sellCoinTrade($op_uid,$goods_discount,$tid = 0)
    {


        trace('uid'.$op_uid,"debug");
        trace('goods_discount'.$goods_discount,"debug");
        trace('tid'.$tid,"debug");
            // 匹配算法
        $tid = $this->matchingTrade($op_uid,$goods_discount,$tid);

        // 如果找到匹配记录进行交易
        if($tid)
        {
            //trace("如果找到匹配记录进行交易".$tid);
            $this->sendMsg($tid);
            return 1;
        }
        return 0;
    }

    //发送短消息
    public function sendMsg($tid)
    {
        $member = new Member();
        $trade_model = new NsCoinTradeModel();
        $info = $trade_model->getInfo(['tid' => $tid]);
        $trade_status = $info["trade_status"];
        switch ($trade_status)
        {
            case 1:
                $m_info = $member->getUserInfoByUid($info["post_uid"]);
                $params['mobile'] = $m_info["user_tel"];
                $params['msg'] = '订单已经匹配好了卖家，请您及时登录APP操作';
                $result = runhook('Notify', 'tradeSmsNotify', $params);
                break;
            case 2:
                if($info["op_uid"] != 60912)
                {
                    $m_info = $member->getUserInfoByUid($info["op_uid"]);
                    $params['msg'] = '订单已经付款，请您及时登录APP操作';
                    $params['mobile'] = $m_info["user_tel"];
                    $result = runhook('Notify', 'tradeSmsNotify', $params);
                }
                break;
            case 3:
                $result = 1;
                break;
            default:
                $result = 1;
                break;
        }
        return 1;
    }

    //添加交易
    public function addCoinTrade($post_uid,$trade_type,$trade_status,$coin_count,$coin_price,$add_time,$trade_time,$finish_time,$op_uid = 0)
    {
        $trade_no = time();
        $coin_trade = new NsCoinTradeModel();
        $data = array(
            'post_uid' => $post_uid,
            'trade_type'  => $trade_type,
            'coin_count'  => $coin_count,
            'trade_status' =>$trade_status,
            'coin_price'  => $coin_price,
            'total_price'  => $coin_price*$coin_count,
            'add_time'  => $add_time,
            'trade_time'  => $trade_time,
            'finish_time'  => $finish_time,
            'trade_no'  => $trade_no,
            'op_uid' => $op_uid
        );
        $coin_trade->save($data);
        return 1;
    }

    //删除一个解封申请
    public function delUblockRecords($id)
    {
        $ublock_model = new NsUblockRecordsModel();
        $conditon['id'] = $id;
        $retval = $ublock_model->where($conditon)->delete();;
        return $retval;
    }


    // 获取回复详情
    public function getComplainInfo($tid)
    {
        $coin_model = new NsTradeComplainModel();
        $info = $coin_model->getInfo(['tid'=>$tid],"*");
        return $info;
    }

    // 回复会员一个投诉
    public function modifyTradeComplain($cid,$replay)
    {
        $coin_model = new NsTradeComplainModel();
        $data = ['replay' =>$replay,'replay_time' => time(),'status' => 1];
        $retval = $coin_model->save($data,['cid'=>$cid]);
        return $retval;
    }


    //删除会员一个投诉记录
    public function delTradeComplain($cid)
    {
        $coin_model = new NsTradeComplainModel();
        $conditon['cid'] = $cid;
        $retval = $coin_model->where($conditon)->delete();;
        return $retval;
    }

    //删除会员一个运行的矿机
    public function delRunMillPrice($id)
    {
        $coin_model = new NsRunMillViewModel();
        $conditon['run_mill_id'] = $id;
        $retval = $coin_model->where($conditon)->delete();;
        return $retval;
    }

    // 删除一个客服
    public function delKefu($id)
    {
        $coin_model = new NsKefuModel();
        $conditon['kf_id'] = $id;
        $retval = $coin_model->where($conditon)->delete();;
        return $retval;
    }

    // 删除一个买币规则
    public function buyCoinSendDel($id)
    {
        $coin_model = new NsBuyCoinSendModel();
        $conditon['id'] = $id;
        $retval = $coin_model->where($conditon)->delete();;
        return $retval;
    }

    // 删除一个矿机
    public function delMillPrice($id)
    {
        $coin_model = new NsMillLevelModel();
        $conditon['level_id'] = $id;
        $retval = $coin_model->where($conditon)->delete();;
        return $retval;
    }

    // 删除一条币价记录
    public function delCoinPrice($id)
    {
        //trace($id,"debug");
        $coin_price = new NsCoinPriceModel();
        $conditon['cpid'] = $id;
        $retval = $coin_price->where($conditon)->delete();;
        return $retval;
    }

    //确认收款一条记录
    public function confirmPayCoinTrade($tid)
    {
        $coin_trade = new NsCoinTradeModel();
        $coin_trade->startTrans();
        try {
            $info = $coin_trade->where(['tid' => $tid])->lock(true)->find();
            //$info = $coin_trade->getInfo(['tid'=> $tid],"trade_status");
            $trade_status = $info["trade_status"];
            $post_uid = $info["post_uid"];
            $op_uid = $info["op_uid"];

            if($op_uid != $this->uid)
            {
                $coin_trade->rollback();
                return 0;
            }
            if ($trade_status == 3) {
                $coin_trade->rollback();
                return 0;
            }

            $data = array(
                'trade_status' => 3,
                'finish_time' => time()
            );

            $coin_trade->save($data, ['tid' => $tid]);
            $res = $this->payCal($tid);

            $this->clearCacheTradeList($this->uid);
            $this->clearCacheTradeList($post_uid);

            $coin_trade->commit();
            $res = 1;
        }catch (\Exception $e) {
            $coin_trade->rollback();
            $res = 0;
        }

        if($res)
        {
            $this->sendMsg($tid);
        }
        return $res;
    }

    //确认收款后计算
    public function payCal($tid)
    {
        $coin_trade = new NsCoinTradeModel();
        $trade_info = $coin_trade->getInfo(['tid'=> $tid],"*");

        $buy_uid = $trade_info["post_uid"];
        $coin_count = $trade_info["coin_count"];

        //$op_uid = $trade_info["op_uid"];

        $member = new MemberService();

        //$member->updateUserInfoByUid($buy_uid,['source'=>2]);
        // 增加币
        $retval = $member->addMemberAccount(0, 1, $buy_uid, $coin_count, '点对点交易' );

        //2019-08-16
        //$retval = $member->addMemberAccount(0, 5, $buy_uid, $coin_count, '点对点交易，订单编号'.$tid );
        //$retval = $member->addMemberAccount(0, 2, $buy_uid, $coin_count , '点对点交易,订单编号：' . $tid);


        // 为买家自己及增加购买数量
        $retval = $this->addBuyCoinCount($buy_uid,$coin_count);


        // 增加完成订单数量
        $config = new Config();
        $key = "delete_coin_trade";
        $info = $config->getConfig(0, $key);
        $match_rate = $info["value"];
        $match_rate = $match_rate + 1;

        $time = time();
        if($time % 1 == 0)
        {
            $array[] = array('instance_id' => $this->instance_id,'key' => 'delete_coin_trade', 'value' => $match_rate);
            $res = $config->setConfig($array);
            Cache::set("delete_coin_trade", NULL, 0);
        }




        /*
        if($match_rate == 50)
        {
            $params['mobile'] = '';
            $params['msg'] = '订单已经匹配好了卖家，请您及时登录APP操作';
            $result = runhook('Notify', 'tradeSmsNotify', $params);
        }
        */
        return $retval;
    }

    // 获取交易中心购买单 显示今天的购买订单
    public function getAllCoinList($trade_type = 0)
    {
        $coin_price = new NsCoinTradeModel();
        $condition = ['trade_status' => 0,'trade_type' =>$trade_type];
        $list = $coin_price->limit(0, 200)->where($condition)->order('tid desc')->select();
        foreach ($list as $k => $v) {
            $member = new MemberService();
            if($v['trade_type'] == 0)
            {
                $info = $member->getUserInfoByUid($v['post_uid']);
            }
            else
            {
                $info = $member->getUserInfoByUid($v['op_uid']);
            }

            $list[$k]['real_name'] = $info['real_name'];
            $list[$k]['sell_trade_count'] = $info['sell_trade_count'];
            $list[$k]['sell_trade_rate'] = $info['sell_trade_rate'];
        }
        return $list;
    }
    // 为买家自己及9代增加购买数量
    public function addBuyCoinCount($uid,$coin_count)
    {
        $member = new MemberService();
        $info = $member->getUserInfoByUid($uid);
        $parent_id = $info["parent_id"];
        $n = 1;

        $member_account = new NsMemberAccountModel();
        $info = $member_account->getInfo(['uid' => $uid],'hpcoin,donation');
        $hpcoin = $info["hpcoin"];
        $donation = $info["donation"];
        $sum_hpcoin = $hpcoin + $coin_count;
        $sum_donation = $donation + $coin_count;
        $res = $member_account->save(['hpcoin'=>$sum_hpcoin,'donation'=>$sum_donation],['uid'=>$uid]);

        /*
        while ($parent_id and $n<=9)
        {
            $member_account = new NsMemberAccountModel();
            $info = $member_account->getInfo(['uid' => $parent_id],'team_hash,zhitui_num');
            $team_hash = $info["team_hash"];
            $sum_team_hash = $team_hash + $coin_count;

            if($n == 1)
            {
                $sum_zhitui_num = $info["zhitui_num"] + $coin_count;
                $res = $member_account->save(['zhitui_num'=>$sum_zhitui_num],['uid'=>$parent_id]);
            }

            // 获取推荐人
            $info = $member->getUserInfoByUid($parent_id);
            $parent_id = $info["parent_id"];
            $n = $n + 1;
        }
        */
        return 1;
    }


    // 三代买矿机列表
    public function getFloorList($page_index = 1, $page_size = 0, $condition = '', $order = '')
    {
        $floor_view = new NsFloorModel();
        //trace($condition,"debug");
        $floor_list = $floor_view->getViewList($page_index, $page_size, $condition, $order);
        return $floor_list;
    }
    // 支付一条众筹记录
    public function payFundTrade($fid,$pay_pic)
    {
        $coin_trade = new NsCoinFundModel();
        $info = $coin_trade->getInfo(['fid'=>$fid],"op_uid,trade_status");
        $trade_status = $info["trade_status"];
        if ($trade_status == 2)
        {
            return 0;
        }
        $data = array(
            'pay_pic' => $pay_pic,
            'trade_status' => 2,
            'pay_time' => time()
        );
        //trace($data);
        $coin_trade->save($data,['fid'=> $fid]);
        return 1;
    }


    // 支付一条记录
    public function payCoinTrade($tid)
    {
        $coin_trade = new NsCoinTradeModel();
        $info = $coin_trade->getInfo(['tid'=>$tid],"op_uid,trade_status");
        $op_uid = $info['op_uid'];
        $trade_status = $info["trade_status"];
        $total_price = $info["total_price"];
        $pay_pic = $info["pay_pic"];
        if ($trade_status == 2)
        {
            return 0;
        }

        $data = array(
            'trade_status' => 2,
            'pay_time' => time()
        );

        //trace($data);
        $coin_trade->save($data,['tid'=> $tid]);
        $this->clearCacheTradeList($this->uid);
        $this->clearCacheTradeList($op_uid);



        $this->sendMsg($tid);
        return 1;
    }


    //清楚缓存数据
    public function clearCacheTradeList($uid)
    {
        trace("订单缓存数据清除操作");
        Cache::set("cacheTradeList_all_".$uid,NULL);
        Cache::set("cacheTradeList_buy_".$uid,NULL);
        Cache::set("cacheTradeList_finish_".$uid,NULL);
    }


    //删除一条众筹交易记录
    public function delFunCoinTrade($id)
    {
        $fund_trade = new NsCoinFundModel();
        $count = $fund_trade->getCount(['fid'=>$id,'uid'=>$this->uid,'trade_status'=>0]);
        if($count)
        {
            $res = $fund_trade->where(['fid'=>$id])->delete();
        }
        return 1;
    }


    //删除一条交易记录
    public function delCoinTrade($id)
    {
        $coin_trade = new NsCoinTradeModel();
        $info = $coin_trade->getInfo(['tid'=>$id],"post_uid,op_uid");
        $post_uid = $info["post_uid"];
        $op_uid = $info["op_uid"];

        if($this->uid != $post_uid)
        {
            return -1;
        }
        $this->clearCacheTradeList($post_uid);
        $this->clearCacheTradeList($op_uid);

        $res = $coin_trade->where(['tid'=>$id])->delete();
        return $res;
    }

    //完成一条交易记录
    public function finishCoinTrade($id,$uid)
    {
        $coin_trade = new NsCoinTradeModel();
        $data = array(
            'trade_status' =>1,
            'op_uid' =>$uid,
            'trade_time' => date("Y-m-d H:i:s", time()),
            'finish_time' => date("Y-m-d H:i:s", time())
        );
        $coin_trade->save($data,['tid'=> $id]);

        $trade_info = $coin_trade->getInfo(['tid'=> $id],"*");

        $total_price = $trade_info["total_price"];
        $coin_count = $trade_info["coin_count"];
        $post_uid = $trade_info["post_uid"];
        $op_uid = $trade_info["op_uid"];
        $trade_no = $trade_info["trade_no"];

        $buy_uid = $post_uid;
        $sell_uid = $op_uid;

        $member = new MemberService();
        //扣用户钱
        $retval = $member->addMemberAccount(0, 2, $buy_uid, 0 - $total_price, '点对点交易,凭证：' . $trade_no, 12);
        $retval = $member->addMemberAccount(0, 2, $sell_uid, $total_price, '点对点交易,凭证：' . $trade_no, 12);
        //给用户币
        $retval = $member->addMemberAccount(0, 7, $buy_uid,  $coin_count, '点对点交易,凭证：' . $trade_no, 12);
        $retval = $member->addMemberAccount(0, 7, $sell_uid, 0 - $coin_count, '点对点交易,凭证：' . $trade_no, 12);

        $this->clearCacheTradeList($post_uid);
        $this->clearCacheTradeList($op_uid);
        return 1;
    }

    // 客服列表
    public function getKfList($page_index = 1, $page_size = 0, $condition = '', $order = '', $field = '*')
    {
        $member_level = new NsKefuModel();
        return $member_level->pageQuery($page_index, $page_size, $condition, $order, $field);
    }

    // 买币赠送
    public function getBuyCoinSendList($page_index = 1, $page_size = 0, $condition = '', $order = '', $field = '*')
    {
        $member_level = new NsBuyCoinSendModel();
        return $member_level->pageQuery($page_index, $page_size, $condition, $order, $field);
    }

    // 矿机列表
    public function getMillLevelList($page_index = 1, $page_size = 0, $condition = '', $order = '', $field = '*')
    {
        //trace("dddddddddddddd","debug");

        $member_level = new NsMillLevelModel();
        $list =  $member_level->pageQuery($page_index, $page_size, $condition, $order, $field);

        return $list;
    }

    public function getMillInfoByID($id)
    {
        $member_level = new NsMillLevelModel();
        $info = $member_level->getInfo(['level_id'=>$id],"*");
        return $info;
    }
    // 申请解封列表
    public function getUblockList($page_index = 1, $page_size = 0, $condition = '', $order = '')
    {
        $mill_view = new NsUblockViewModel();
        $run_list = $mill_view->getViewList($page_index, $page_size, $condition, $order);
        return $run_list;
    }


    // 获取用户投诉列表
    public function getTradeComplainList($page_index = 1, $page_size = 0, $condition = '', $order = '')
    {
        $trade_complain_list = new NsTradeComplainModel();
        $list = $trade_complain_list->getViewList($page_index, $page_size, $condition, $order);
        return $list;
    }

    // 更新矿机产量
    public function updateMillReceived($run_mill_id,$total_count)
    {
        $run_mill = new NsRunMillModel();
        $res = $run_mill->save(['received' => $total_count],['run_mill_id' => $run_mill_id]);
        return $res;
    }

    // 运行中的矿机列表
    public function getRunMillList($page_index = 1, $page_size = 0, $condition = '', $order = '')
    {
        $mill_view = new NsRunMillViewModel();
        $run_list = $mill_view->getViewList($page_index, $page_size, $condition, $order);
        return $run_list;
    }

    // 给某人相对数量的矿机
    public function givePool($uid,$level_id,$path_tree='',$add_hash=0,$parent_id = 0,$base = 0,$day_product = 0,$desc = '',$number = 0)
    {

        //获取运行时间
        $mill = new NsMillLevelModel();

        $info = $mill->getInfo(['level_id'=>$level_id],"*");
        $all_day = $info['all_day'];


        $create_time = time();
        $die_time = $create_time + 60*60*24*$all_day;
        $run_mill = new NsRunMillModel();
        $data = [
            'uid' => $uid,
            'level_id' => $level_id,
            'create_time' => $create_time,
            'die_time' => $die_time,
            'path_tree' =>$path_tree,
            'add_hash' => $add_hash,
            'parent_id' =>$parent_id,
            'status' => 1,
            'base' => $base,
            'day_product' => $day_product,
            'desc' =>$desc,
            'number' =>$number
        ];
        $res = $run_mill->save($data);
    }


    // 获得小猪农场id
    public function getSmallMillLevel()
    {
        $member_level = new NsMillLevelModel();
        $info = $member_level->getFirstData(['status'=>1],'day_product asc');
        return $info['level_id'];
    }

    // 更新已经产出数量
    public function updateAlProduct($run_mill_id,$al_product,$status = 1)
    {
        $run_mill = new NsRunMillModel();
        $res = $run_mill->save(['al_product' => $al_product,'status' =>$status],['run_mill_id' => $run_mill_id]);
        return $res;
    }

    // 收割产出
    public function receivedProductBase($differ)
    {
        $member = new MemberService();
        $retval = $member->addMemberAccount(0, 2, $this->uid, $differ, '矿机领取');
        return 1;
    }

    // 收割产出
    public function receivedProduct($differ)
    {

        $member = new MemberService();
        $retval = $member->addMemberAccount(0, 1, $this->uid, $differ, '矿机领取');
        // 9代奖励
        //$this->sendatNineReword($this->uid,$differ);
        $user = new UserModel();
        $time = time();
        $user->save(['last_get_time'=>$time],['uid'=>$this->uid]);
        return 1;
    }

    // 发送at9代奖励
    public function sendatNineReword($uid,$release_count)
    {
        $member = new MemberService();
        $info = $member->getUserInfoByUid($uid);
        $parent_id = $info["parent_id"];
        $n = 1;
        while ($parent_id and $n<=9)
        {
            switch ($n) {
                case 1:
                    $rate = 0.02;
                    break;
                case 2:
                    $rate = 0.01;
                    break;
                case 3:
                    $rate = 0.005;
                    break;
                case 4:
                    $rate = 0.005;
                    break;
                case 5:
                    $rate = 0.003;
                    break;
                case 6:
                    $rate = 0.003;
                    break;
                case 7:
                    $rate = 0.001;
                    break;
                case 8:
                    $rate = 0.001;
                    break;
                case 9:
                    $rate = 0.001;
                    break;
                default:
                    $rate = 0;
                    break;
            }

            $account = $release_count * $rate;
            $member_account = new NsMemberAccountModel();
            $info = $member_account->getInfo(['uid' => $parent_id],"bonus_total");
            $bonus_total = $info["bonus_total"] + $account;
            $res = $member_account->save(['bonus_total'=>$bonus_total],['uid'=>$parent_id]);
            $retval = $member->addMemberAccount(0, 1, $parent_id, $account, $n.'代团队奖励');

            // 获取推荐人
            $info = $member->getUserInfoByUid($parent_id);
            $parent_id = $info["parent_id"];
            $n = $n + 1;
        }
    }


    // 获取有效农场
    public function getMyRunMillCoint()
    {
        $mill = new NsMillLevelModel();
        $list = $mill->getQuery([],"*","level_id asc");
        trace($list,"debug");
        foreach ($list as $k => $v)
        {
            $list[$k]["count"] = $this->getRunMillCount($v['level_id']);
        }
        return $list;
    }

    // 有效农场
    public function getRunMillCount($level_id = 0)
    {
        $run_mill = new NsRunMillModel();
        $conditon = ['uid'=> $this->uid,'status' => 1];
        if($level_id)
        {
            $conditon["level_id"] = $level_id;
        }
        $count = $run_mill->getCount($conditon);
        return $count;
    }

    // 累计产量
    public function getAllMillProduct()
    {
        $run_mill = new NsRunMillModel();
        $count = $run_mill->getSum(['uid'=> $this->uid],"received");
        return $count;
    }

    // 每日累计产量
    public function getAllDayProduct()
    {
        $run_mill = new NsRunMillModel();
        $count = $run_mill->getSum(['uid'=> $this->uid,'status'=>1],"day_product");
        return $count;
    }

    // 每日累计产量
    public function getAllTokenProduct()
    {
        $run_mill = new NsTokenModel();
        $count = $run_mill->getSum(['uid'=> $this->uid,'status'=>1],"get_money");
        return $count;
    }

    // 智能值
    public function getSmartValue()
    {
        $run_mill = new NsRunMillModel();
        $now = time();
        $count = $run_mill->getSum(['uid'=> $this->uid],"add_hash");
        return $count;
    }

    // 加成智能值
    public function getReferSmartValue()
    {
        $run_mill = new NsRunMillModel();
        $now = time();
        $count = $run_mill->getSum(['parent_id'=> $this->uid],"add_hash");
        return $count*0.05;
    }

    // 获取今天卖出已经卖出的币数量
    public function getTodaySellCoinCount()
    {
        $coin_price = new NsCoinTradeModel();
        $start_time = date('Y-m-d');
        $condition = array(
            'add_time' => array(
                'EGT',
                getTimeTurnTimeStamp($start_time)
            ),
            'op_uid' => $this->uid,
            'trade_status' => ['neq',-1]
        );
        $account = $coin_price->getSum($condition,"coin_count");
        return $account;
    }

    // 获取今天卖出的数量
    public function getTodaySellCount()
    {
        $coin_price = new NsCoinTradeModel();
        $start_time = date('Y-m-d');
        $condition = array(
            'trade_time' => array(
                'EGT',
                getTimeTurnTimeStamp($start_time)
            ),
            'op_uid' => $this->uid,
            'trade_status' => ['neq',-1]
        );
        $account = $coin_price->where($condition)->count();
        return $account;
    }

    // 获取昨天购买币的数量
    public function getYestodayBuyCoinCount()
    {
        $coin_price = new NsCoinTradeModel();
        $today_time = strtotime(date("Y-m-d"),time());
        $condition = array(
            'add_time' => [['lt',$today_time],['gt',1556121600]],
            'trade_status' => 3,
            'post_uid|op_uid' => $this->uid
        );
        $info = $coin_price->getFirstData($condition,"tid desc");

        if($info)
        {
            if($info["post_uid"] == $this->uid)
            {
                return $info["coin_count"];
            }
            else
            {
                $add_time = $info["add_time"];
                $start_time = strtotime(date("Y-m-d",$add_time));
                //trace("这里".$start_time);
                if($start_time < 1556121600)
                {
                    return 0;
                }
                $condition = array(
                    'add_time' => [['gt',$start_time],['lt',$today_time]],
                    'trade_status' => 3,
                    'post_uid' => $this->uid
                );
                $info = $coin_price->getFirstData($condition,"tid desc");
                if($info)
                {
                    return $info["coin_count"];
                }
                return 0;
            }
        }
        else
        {
            return 0;
        }

    }

    // 获取昨天购买的数量
    public function getYestodayBuyCount()
    {
        $coin_price = new NsCoinTradeModel();
        $today_time = strtotime(date("Y-m-d"),time());
        $yestoday_time = strtotime(date("Y-m-d",strtotime("-1 day")));
        $condition = array(
            'add_time' => [['lt',$today_time],['gt',1555948800]],
            'trade_status' => 3,
            'post_uid|op_uid' => $this->uid
        );
        $info = $coin_price->getFirstData($condition,"tid desc");

        if($info)
        {
            if($info["post_uid"] == $this->uid)
            {
                return 1;
            }
            else
            {
                $add_time = $info["add_time"];
                $start_time = strtotime(date("Y-m-d",$add_time));
                //trace("这里".$start_time);
                if($start_time < 1555948800)
                {
                    return 0;
                }
                $condition = array(
                    'add_time' => [['gt',$start_time],['lt',$today_time]],
                    'trade_status' => 3,
                    'post_uid' => $this->uid
                );
                $count = $coin_price->getCount($condition);
                return $count;
            }
        }
        else
        {
            //trace("这里2");
            return 0;
        }

    }



    // 获取今天购买的数量
    public function getTodayBuyCount()
    {
        $coin_price = new NsCoinTradeModel();
        $start_time = date('Y-m-d');
        /*
        $condition = array(
            'add_time' => array(
                'EGT',
                getTimeTurnTimeStamp($start_time)
            ),
            'trade_status' => 0,
            'post_uid' => $this->uid
        );
        */
        $condition = array(
            'trade_status' => 0,
            'post_uid' => $this->uid
        );


        $account = $coin_price->where($condition)->count();
        return $account;
    }


    // 获取最小tid
    public function getMinTid($uid)
    {
        $coin_trade = new NsCoinTradeModel();
        $info = $coin_trade->getFirstData(['post_uid'=>$uid],"level_id asc");
        if($info)
        {
            return $info['level_id'];
        }else
        {
            return 1000;
        }
    }


    // 获取上次购买的数量
    public function getLastBuyCoount($uid)
    {
        $coin_trade = new NsCoinTradeModel();
        $info = $coin_trade->getFirstData(['post_uid'=>$uid],"tid desc");
        if($info)
        {
            return $info['coin_count'];
        }else
        {
            return 0;
        }
    }



    // 获取上次挂单时间
    public function getLastPostDiffer_time()
    {
        $last_post_time = Cache::get("last_post_time" . $this->uid);
        $now_time = time();
        if($last_post_time == "")
        {
            return 87000;
        }

        $second = $now_time-$last_post_time;

        return $second;
    }


    // 已经挂单时间 众筹单
    public function getFundTradePostTime($fid)
    {
        $fund_trade = new NsCoinFundModel();
        $condition = ['fid' => $fid];
        $info = $fund_trade->getInfo($condition,"add_time","fid desc");
        $add_time = $info["add_time"];
        $enddata = time();
        $fenzhong=floor(($enddata-$add_time)%86400/60);
        //trace($second."秒");
        return $fenzhong;
    }

    // 已经挂单时间
    public function getPosttime($tid)
    {
        $coin_price = new NsCoinTradeModel();
        $condition = ['tid' => $tid];

        $info = $coin_price->getInfo($condition,"add_time","tid desc");

        $add_time = $info["add_time"];
        $enddata = time();
        $fenzhong=floor(($enddata-$add_time)%86400/60);
        //trace($second."秒");
        return $fenzhong;
    }


    // 获取矿机详情
    public function getMillInfo($id)
    {
        $run_mill = new NsRunMillModel();
        $info = $run_mill->getInfo(['run_mill_id' =>$id]);
        $info['may_received'] = $info['al_product'] - $info['received'];
        $now = time();
        $create_time = $info['create_time'];
        $mill = new NsMillLevelModel();
        $mill_level_info = $mill->getInfo(['level_id' => $info["level_id"]]);
        $info['level_name'] = $mill_level_info["level_name"];
        // 每秒产量
        $info['second_product'] = $mill_level_info["day_product"]/(3600*12);
        //运行小时数
        $info['hour'] = floor(($now - $create_time)/3600);
        $info["total_product"] = $mill_level_info["total_product"];
        $hour=($now-$create_time)/3600;
        $info["day_product"] = $mill_level_info["day_product"];
        $al_product = $info["day_product"]/24*$hour;

        $res = $this->updateAlProduct($id,$al_product);

        $info["total_product"] = $al_product;

        $info["al_product2"] = $info['second_product']+$al_product;

        return $info;
    }


    /**
     * 获取所有会员总数
     */
    public function getAllMillLevelSum($uid = 0)
    {
        $mill_level = new NsMillLevelModel();
        $condition =  array(
            'shop_id' => 0
        );
        $list = $mill_level->getQuery($condition,'*',"level_id asc");

        $infos = array();

        foreach ($list as $k => $v)
        {
            $infos[$k]["level_id"] = $list[$k]["level_id"];
            $infos[$k]["level_name"] = $list[$k]["level_name"];
            $infos[$k]["mill_count"] = $this->getMillLevelSum($list[$k]["level_id"],$uid);
        }
        $k = count($infos);
        $infos[$k]["level_name"] = "全部矿机";
        $infos[$k]["mill_count"] = $this->getMillLevelSum(0,$uid);

        return $infos;
    }


    /**
     * 获取矿机总数
     * @param unknown $uid
     */
    public function getMillLevelSum($level_id,$uid = 0,$start_data = '',$end_data = '')
    {
        $mill = new NsRunMillModel();
        $condition =  array();

        if ($level_id)
        {
            $condition["level_id"] = $level_id;
        }

        if($uid)
        {
            $condition["uid"] = $uid;
        }


        $mill_count = $mill->getCount($condition);
        if (!empty($mill)) {
            return $mill_count;
        } else {
            return 0;
        }
    }


    // 批量锁定矿机
    public function lockRunMill($uid,$lock)
    {
        trace("批量锁定矿机","debug");
        $mill = new NsRunMillModel();
        $res = $mill->save(['lock'=>$lock],['uid'=>$uid]);
    }

    // 锁定金额
    public function updateShare()
    {
        $member = new Member\MemberAccount();
        $info = $member->getMemberAccountInfo($this->uid);
        $share = $info['share'];
        $condition["nrm.uid"] = $this->uid;
        $condition["nrm.status"] = 1;
        $list = $this->getRunMillList(1, 0, $condition);
        $run_list = $list["data"];
        $result = 0;
        foreach ($run_list as $key => $item) {

            $price = $item["price"];
            $result = $result + $price;
        }

        if($share < $result)
        {
            $member_model = new NsMemberAccountModel();
            $res = $member_model->save(['share'=>$result],['uid'=>$this->uid]);
            $share = $result;
        }
        return $share;


    }

    // 剩余可产数量
    public function totalMillReceive()
    {
        $condition["nrm.uid"] = $this->uid;
        $condition["nrm.status"] = 1;

        $list = $this->getRunMillList(1, 0, $condition);
        $run_list = $list["data"];
        $total_product = 0;
        foreach ($run_list as $key => $item) {

            $price = $item["price"];
            $received = $item["received"];
            $total_product_per = $item["total_product"];
            $total_product = $total_product + $total_product_per - $received;
        }
        return $total_product;
    }

    // 运行中的矿机列表
    public function getTokenList($page_index = 1, $page_size = 0, $condition = '', $order = '')
    {
        $mill_view = new NsTokenViewModel();
        $run_list = $mill_view->getViewList($page_index, $page_size, $condition, $order);
        return $run_list;
    }


    // 添加通令
    public function addToken($uid,$account,$die_time,$get_money)
    {
        $mill_model = new NsTokenModel();
        $data = array(
            'uid' => $uid,
            'status' => 1,
            'total_account' => $account,
            'get_money' => $get_money,
            'add_time' => time(),
            'send_time' => $die_time
        );
        $mill_model->save($data);
        return 1;
    }


    // 全部释放
    public function release()
    {

        $today_time = strtotime(date('Y-m-d'));
        $yestoday = strtotime(date("Y-m-d",strtotime("-1 day")));
        //$today_time = strtotime("+1 day");
        $condition['status'] = 1;
        $condition['lock'] = 0;
        $condition["send_time"] = [
            [
                "<=",
                $today_time
            ],
            [
                ">=",
                $yestoday
            ]
        ];

        trace("释放","debug");
        trace($condition,"debug");
        $token = new NsTokenModel();
        $list = $token->limit(0, 100)->where($condition)->order('id desc')->select();
        trace($list,"debug");
        $member = new Member();
        foreach($list as $value)
        {
            $lock_status = $this->getRunMillLock($value['uid'],$today_time);
            trace('当前自动复投状态：'.$lock_status,"debug");
            if($lock_status == 0)
            {
                $retval = $member->addMemberAccount(0, 2, $value['uid'], $value['total_account'], "循环增值本金");
            }
            $retval = $member->addMemberAccount(0, 6, $value['uid'], $value['get_money'], "循环增值收益");

            $this->updateToken($value['id']);
        }

        $condition = [];
        $condition['status'] = 1;
        $condition["die_time"] = [
            [
                "<=",
                $today_time
            ]
        ];
        $run_model = new NsRunMillModel();
        $list = $run_model->limit(0, 100)->where($condition)->order('run_mill_id desc')->select();

        //获取所有到期的理财包
        foreach($list as $value)
        {
            trace('当前到期run_mill_id'.$value['run_mill_id'],"debug");

            //进行自动复投
            if($value['lock'] == 1)
            {
                $member_account_model = new NsMemberAccountModel();
                $member_account_model->startTrans();
                $number = $value['number'];
                $uid = $value['uid'];
                $id = $value['level_id'] + 1;
                $member = new MemberService();
                $member->addMemberMill($uid,$id,1,2,'',$number);

                $usermodel = new UserModel();
                $auto_id = $id;
                if($id == 3)
                {
                    $id = 0;
                }
                $res= $usermodel->save(['vip'=>$id+1,'salary_get'=>1],['uid'=>$uid]);

                $mill = new NsMillLevelModel();
                if($auto_id <= 0 or $auto_id > 3){$auto_id = 3;}
                trace('auto_id'.$auto_id,"debug");
                $info = $mill->getInfo(['level_id' => $auto_id]);

                $die_time = time() + 60*60*24*$info["all_day"];
                $member->calculateSalary($uid,$info,$number,$die_time);
                $member_account_model->commit();
                $retval = 1;
            }
            $this->updateRunMill($value['run_mill_id']);
        }
        // 更改释放时间
        return 1;
    }

    // 获取自动复投状态
    public function getRunMillLock($uid,$today_time)
    {
        $run_mill = new NsRunMillModel();
        $res = $run_mill->getInfo(['uid'=>$uid,'status'=>1,'die_time'=>['<=',$today_time]],"*");
        if($res['lock']==1){
            return 1;
        }
        else
        {
            return 0;
        }
    }

    public function updateRunMill($run_mill_id)
    {
        $token = new NsRunMillModel();
        $res = $token->save(['status'=>2],['run_mill_id'=>$run_mill_id]);
        trace("更新结果".$res,"debug");
    }

    public function updateToken($id)
    {
        $token = new NsTokenModel();
        $res = $token->save(['release_time'=>time(),'status'=>2],['id'=>$id]);
        trace("更新结果".$res,"debug");
    }

    //删除会员一个运行的矿机
    public function delTokenDel($id)
    {
        $coin_model = new NsTokenModel();
        $conditon['id'] = $id;
        $retval = $coin_model->where($conditon)->delete();;
        return $retval;
    }


    public function releaseFrozenCoin($id){
        $today_time = strtotime(date('Y-m-d'));
        $member_account = new NsMemberAccountModel();
        $info = $member_account->getInfo(['id'=>$id],"*");

        //if($info and $info['salary'] > 0 )
        if($info and $info['credit'] > 0){
            $min_point = $info['credit']*0.001;
            $min_point = round($min_point,2);
            //trace('释放银币数量'.$min_point,"debug");
            //trace('用户ID'.$uid,"debug");

            // 给用户自己释放币
            if($min_point > 0){
                $member = new MemberService();
                $member->addMemberAccount(0,8,$info['uid'],0-$min_point,'老会员',21);
                $member->addMemberAccount(0,4,$info['uid'],$min_point,'老会员',21);
            }
        }

        if($info and $info['salary'] > 0 and $info['last_release_time'] != $today_time)
        {

            //获取100天内的rank_point
            //$member_account_record = new NsMemberInvestRecordsModel();

            //$real_rank_point = $member_account_record->getSum(['uid'=>$info['uid'],'account_type'=>4,'release_ok'=>0,'lock'=>0,'number'=>['>',0]],"number");

            $real_rank_point = $info['salary'];


            $data['last_release_time'] = $today_time;
            $retval = $member_account->save($data,['id'=>$id]);

            // 释放
            $this->releaseCoin($info['uid'],$real_rank_point,$info['salary'],'释放',21,$real_rank_point);

        }
        return 1;
    }



    // 释放币
    public function releaseCoin($uid,$rank_point,$salary,$text,$from_type,$refer_real_rank_point)
    {
        $point = $rank_point * 3 /1000;
        $refer_point = $refer_real_rank_point * 3 /1000;
        $member = new Member();

        $min_point = min($point,$salary);
        $refer_min_point = min($refer_point,$salary);

        // 保留2位码
        $refer_min_point = round($refer_min_point,2);
        $min_point = round($min_point,2);

        //trace('释放银币数量'.$min_point,"debug");
        //trace('用户ID'.$uid,"debug");

        // 给用户自己释放币
        if($min_point > 0){
            $member->addMemberAccount(0,4,$uid,0-$min_point,$text,$from_type);
            $member->addMemberAccount(0,1,$uid,$min_point,$text,$from_type);
        }

        // 推荐奖金
        $salary = new Salary();
        $salary->releaseReferSalary($uid,$refer_min_point);
        $salary->releaseGradeSalary($uid,$min_point);

        // 下级释放
        //$salary->releaseDownSalary($uid,$refer_min_point);
        //$salary->releaseDown2Salary($uid,$refer_min_point);
    }


}
